package com.edgegateway.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.*;

/**
 * @AUTHOR Doooxu
 * @DATE 2022/10/28
 * @DESCRIBE
 */
public class TelnetUtil {

    /**
     * 测试telnet 机器端口的连通性
     * @param hostname
     * @param port
     * @param timeout
     * @return
     */
    public static boolean telnet(String hostname, int port, int timeout){
        Socket socket = new Socket();
        boolean isConnected = false;
        try {
            socket.connect(new InetSocketAddress(hostname, port), timeout); // 建立连接
            isConnected = socket.isConnected(); // 通过现有方法查看连通状态
//            System.out.println(isConnected);    // true为连通
        } catch (IOException e) {
            System.out.println("false");        // 当连不通时，直接抛异常，异常捕获即可
        }finally{
            try {
                socket.close();   // 关闭连接
            } catch (IOException e) {
                System.out.println("false");
            }
        }
        return isConnected;
    }

    /**
     * 检测URL是否能连通
     * @param URL
     * @return
     */
    public static boolean checkUrl(String URL) {
        try{
            URL url = new URL(URL);
            HttpURLConnection connection = (HttpURLConnection) url .openConnection();
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("User-Agent", "Mozilla/4.0");
            connection.connect();
            connection.setInstanceFollowRedirects(false);
            connection.setConnectTimeout(500);
            if(connection.getResponseCode()==200) {//判断状态码
                String htmlCode="";
                InputStream in = connection.getInputStream();
                byte[] buffer = new byte[500];
                in.read(buffer);
                htmlCode = new String(buffer);
                if( htmlCode.contains("错误页") || htmlCode.contains("{\"message\":\"请求的URI地")) {//拿到返回内容判断是否返回的是错误页
                    return false;
                }
            }else {
                return false;
            }
        }catch(IOException e){
            return false;
        }

        return true;
    }

}
